package com.quyeying.utils.redis;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quyeying.entity.TblOrderBaseEntity;
import com.quyeying.enums.SysConfigConstant;
import com.quyeying.enums.TblOrderBaseEnum;
import com.quyeying.service.TblOrderBaseService;
import com.quyeying.service.TblOrderStatusRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * @ClassName RedisKeyExpirationListener
 * @Description TODO
 * @Author Jll
 * @Date 2022/7/26 10:42
 * @Version 1.0
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Resource
    private TblOrderBaseService tblOrderBaseService;
    @Resource
    private TblOrderStatusRecordService tblOrderStatusRecordService;

    /**
     * Redis失效事件 key
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expireKey = message.toString();
        System.out.println(expireKey);
        // TODO: 这里写业务逻辑
        log.info("redis key过期：{}" + expireKey);
        //业务逻辑处理。。。
        if(expireKey.contains(SysConfigConstant.SYS_PREFIX)) {
            log.info("处理订单超时未付款：{}" + expireKey);
            String orderNo = expireKey.replace(SysConfigConstant.SYS_PREFIX,"");
            log.info("处理单号：{}" + orderNo);
            //处理取消订单操作
            QueryWrapper<TblOrderBaseEntity> tblOrderBaseEntityQueryWrapper = new QueryWrapper<>();
            tblOrderBaseEntityQueryWrapper.eq("order_no", orderNo);
            TblOrderBaseEntity tblOrderBase = tblOrderBaseService.getOne(tblOrderBaseEntityQueryWrapper);
            if (!ObjectUtils.isEmpty(tblOrderBase)){
                tblOrderBaseService.cancelOrder(tblOrderBase.getId(), 0);
            }

        }
    }


}
